import { Toast } from 'vant'

Toast.setDefaultOptions({ duration: 2000 }) // 将所有 Toast 的展示时长设置为 2000 毫秒
Toast.setDefaultOptions('loading', { forbidClick: true }) // 将所有 loading Toast 设置为背景不可点击 (2.2.10 版本开始支持)

export default {
  // localStorage
  setStore(name, content) {
    if (!name) return
    if (typeof content !== 'string') {
      content = JSON.stringify(content)
    }
    window.localStorage.setItem(name, content)
  },
  getStore(name) {
    if (!name) return
    return window.localStorage.getItem(name)
  },
  removeStore(name) {
    if (!name) return
    window.localStorage.removeItem(name)
  },

  // sessionStorage
  setSessionStore(name, content) {
    if (!name) return
    if (typeof content !== 'string') {
      content = JSON.stringify(content)
    }
    window.sessionStorage.setItem(name, content)
  },
  getSessionStore(name) {
    if (!name) return
    return window.sessionStorage.getItem(name)
  },
  removeSessionStore(name) {
    if (!name) return
    window.sessionStorage.removeItem(name)
  },

  // url参数
  getUrlParam(name) {
    let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)') //构造一个含有目标参数的正则表达式对象
    let r = window.location.search.substr(1).match(reg) //匹配目标参数
    if (r != null) return unescape(r[2])
    return null //返回参数值
  },

  // 返回
  back() {
    window.history.back()
  },

  // 成功并且返回
  successBack(msg) {
    Toast.success(msg)
    setTimeout(() => {
      window.history.back()
    }, 2000)
  },

  loading(msg) {
    Toast.loading({
      message: msg,
      forbidClick: true,
      duration: 0
    })
  },

  closeLoading() {
    Toast.clear()
  }
}
